<?php

namespace api\site\controller;

/**
 * 圈子
 */
class ForumController extends \cmf\controller\RestBaseController
{

    /**
     * 进行测试
     */
    function test()
    {

        echo '<pre>';

        $this->userId = 1;
        $_REQUEST = [
            'name' => '我是圈子abc_' . time(),
            'logo' => '',
            'introduction' => '介绍',
            'type' => '0',
        ];
        try {
            $this->create();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($forum = $th->getResponse()->getData());
        }

        $_REQUEST = [
            'page' => '1',
            'num' => '2',
            'keyword' => 'abc',
        ];
        try {
            $this->lists();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'forum_id' => $forum['data']['forum_id'],
        ];
        try {
            $this->join();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'forum_id' => $forum['data']['forum_id'],
        ];
        try {
            $this->item();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'forum_id' => $forum['data']['forum_id'],
            'content' => '测试发表帖子',
            'imgs' => ['a.jpg', 'b.jpg'],
        ];
        try {
            $this->submit();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($topic = $th->getResponse()->getData());
        }

        $_REQUEST = [
            'topic_id' => $topic['data']['topic_id'],
            'content' => '测试回复帖子',
        ];
        try {
            $this->reply();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($reply = $th->getResponse()->getData());
        }

        $_REQUEST = [
            'reply_id' => $reply['data']['reply_id'],
        ];
        try {
            $this->good();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'topic_id' => $topic['data']['topic_id'],
        ];
        try {
            $this->good();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'topic_id' => $topic['data']['topic_id'],
            'reply_id' => $reply['data']['reply_id'],
            'content' => '测试回复帖子2',
        ];
        try {
            $this->reply();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'forum_id' => $forum['data']['forum_id'],
        ];
        try {
            $this->topics();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'topic_id' => $topic['data']['topic_id'],
        ];
        try {
            $this->topic();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'topic_id' => $topic['data']['topic_id'],
        ];
        try {
            $this->replies();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'reply_id' => $reply['data']['reply_id'],
        ];
        try {
            $this->delete();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }

        $_REQUEST = [
            'topic_id' => $topic['data']['topic_id'],
        ];
        try {
            $this->delete();
        } catch (\think\exception\HttpResponseException $th) {
            var_dump($th->getResponse()->getData());
        }
    }

    /**
     * 获取用户信息
     *
     * @param int $uid
     * @return array|null
     */
    protected static function getUserInfo($uid)
    {
        static $cached = [];
        if (!isset($cached[$uid])) {
            $cached[$uid] = db('user')->where('id', $uid)->field('user_nickname,avatar,last_login_time')->find();
        }
        return $cached[$uid];
    }

    /**
     * 圈子列表
     * 
     * - `page` 第几页
     * - `num` 每页数量
     * - `keyword` 搜索关键词(可选)
     */
    function lists()
    {
        $page = $_REQUEST['page'] ?? 1;
        $num = $_REQUEST['num'] ?? 10;
        $keyword = trim($_REQUEST['keyword'] ?? '');

        $query = db("forum");

        if ($keyword !== '') {
            $keyword = preg_split('/\s/', $keyword, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($keyword as $keyword) {
                $query->whereLike('name', "%$keyword%");
            }
        }

        $list = $query->order('last_time desc,id desc')->page($page, $num)->select()->toArray();
        $total = $query->count();


        foreach ($list as &$item) {
            if ($this->userId === 0) {
                $item['has_join'] = false;
            } else {
                $item['has_join'] = (bool)db('forum_user')->where('forum_id', $item['id'])->where('uid', $this->userId)->count();
            }
        }

        $this->success('查询圈子列表成功', [
            'data' => $list,
            'total' => $total,
        ]);
    }

    /**
     * 创建圈子
     * 
     * - `name` 圈子名称
     * - `logo` 圈子图标
     * - `introduction` 圈子简介
     * - `type` 圈子类型(0免费)
     */
    function create()
    {
        if ($this->userId === 0) {
            return $this->error('请先登录');
        }

        $name = trim($_REQUEST['name'] ?? '');
        $logo = $_REQUEST['logo'] ?? '';
        $introduction = trim($_REQUEST['introduction'] ?? '');
        $type = $_REQUEST['type'] ?? 0;

        if ($name === '') {
            return $this->error('圈子名称不能为空');
        } else if (mb_strlen($name) < 4) {
            return $this->error('圈子名称不能少于4个字符');
        } else if (mb_strlen($name) > 20) {
            return $this->error('圈子名称不能超过20个字符');
        }

        $has = db("forum")->where('name', $name)->count();
        if ($has) {
            return $this->error('圈子名称已存在');
        }

        $r = db("forum")->insertGetId([
            'name' => $name,
            'logo' => $logo,
            'introduction' => $introduction,
            'type' => $type,
            'uid' => $this->userId,
            'create_time' => time(),
        ]);
        if (!$r) {
            return $this->error('新建圈子失败');
        }
        $this->success('创建圈子成功', [
            'forum_id' => $r,
        ]);
    }

    /**
     * 圈子详情
     *
     * - `forum_id` 圈子ID
     */
    function item()
    {
        $forum_id = $_REQUEST['forum_id'] ?? 0;
        $item = db("forum")->where('id', $forum_id)->find();
        if (!$item) {
            return $this->error('圈子不存在');
        }

        $item['user'] = self::getUserInfo($item['uid']);

        if ($this->userId === 0) {
            $item['has_join'] = false;
        } else {
            $item['has_join'] = (bool)db('forum_user')->where('forum_id', $forum_id)->where('uid', $this->userId)->count();
        }

        $this->success('查询圈子详情成功', $item);
    }

    /**
     * 帖子详情
     *
     * - `topic_id` 帖子ID
     */
    function topic()
    {
        $topic_id = $_REQUEST['topic_id'] ?? 0;
        $topic = db("forum_topic")->where('id', $topic_id)->find();
        if (!$topic) {
            return $this->error('帖子不存在');
        }
        $topic['imgs'] = preg_split('/;/', $topic['imgs'], -1, PREG_SPLIT_NO_EMPTY);
        $this->success('查询帖子详情成功', $topic);
    }

    /**
     * 帖子列表
     * 
     * - `forum_id` 圈子ID
     * - `page` 第几页
     * - `num` 每页数量
     */
    function topics()
    {
        $forum_id = $_REQUEST['forum_id'] ?? 0;
        $page = $_REQUEST['page'] ?? 1;
        $num = $_REQUEST['num'] ?? 10;

        $query = db("forum_topic")->where('forum_id', $forum_id);

        $list = $query->order('id desc')->page($page, $num)->select()->toArray();
        $total = $query->count();

        foreach ($list as &$item) {
            $item['user'] = self::getUserInfo($item['uid']);
            $item['imgs'] = preg_split('/;/', $item['imgs'], -1, PREG_SPLIT_NO_EMPTY);
        }

        $this->success('查询帖子列表成功', [
            'data' => $list,
            'total' => $total,
        ]);
    }

    /**
     * 回帖列表
     * 
     * - `topic_id` 帖子ID
     * - `page` 第几页
     * - `num` 每页数量
     */
    function replies()
    {
        $topic_id = $_REQUEST['topic_id'] ?? 0;
        $page = $_REQUEST['page'] ?? 1;
        $num = $_REQUEST['num'] ?? 10;

        $query = db("forum_reply")->where('topic_id', $topic_id)->where('reply_id', 0);

        $list = $query->order('id desc')->page($page, $num)->select()->toArray();
        $total = $query->count();

        foreach ($list as &$item) {
            $item['user'] = self::getUserInfo($item['uid']);
            if ($item['replies_num'] > 0) {
                $item['replies'] = db("forum_reply")->where('reply_id', $item['id'])->order('id desc')->select()->toArray();
                foreach ($item['replies'] as &$item2) {
                    $item2['user'] = self::getUserInfo($item2['uid']);
                }
            } else {
                $item['replies'] = [];
            }
        }

        $this->success('查询回帖列表成功', [
            'data' => $list,
            'total' => $total,
        ]);
    }

    /**
     * 加入圈子
     * 
     * - `forum_id` 圈子ID
     */
    function join()
    {
        $forum_id = $_REQUEST['forum_id'] ?? 0;

        if ($this->userId === 0) {
            return $this->error('请先登录');
        }

        $has = db('forum_user')->where('forum_id', $forum_id)->where('uid', $this->userId)->count();
        if ($has) {
            $this->success('success');
        }

        $forum = db('forum')->where('id', $forum_id)->find();
        if (!$forum) {
            $this->error('圈子不存在');
        }

        $r = db('forum_user')->insert([
            'forum_id' => $forum_id,
            'uid' => $this->userId,
            'time' => time(),
        ]);
        if (!$r) {
            $this->error('加入圈子失败');
        }

        $r = db('forum')->where('id', $forum_id)->update([
            'members_num' => $forum['members_num'] + 1,
        ]);
        if (!$r) {
            $this->error('更新圈子成员数量失败');
        }

        $this->success('加入圈子成功');
    }

    /**
     * 发布帖子
     * 
     * - `forum_id` 圈子ID
     * - `content` 帖子内容
     * - `imgs` 帖子图片(数组,可选)
     */
    function submit()
    {
        $forum_id = $_REQUEST['forum_id'] ?? 0;
        $content = trim($_REQUEST['content'] ?? '');
        $imgs = $_REQUEST['imgs'] ?? [];

        if ($this->userId === 0) {
            return $this->error('请先登录');
        }
        if (!is_array($imgs)) {
            return $this->error('imgs参数必须为数组');
        }

        $forum = db('forum')->where('id', $forum_id)->find();
        if (!$forum) {
            $this->error('圈子不存在');
        }

        if ($forum['uid'] != $this->userId) {
            $this->error('您不是圈子主人无法发表帖子');
        }

        if (mb_strlen($content) < 2) {
            $this->error('帖子内容太少');
        }

        $topic_id = db('forum_topic')->insertGetId([
            'forum_id' => $forum_id,
            'content' => $content,
            'imgs' => implode(';', $imgs),
            'uid' => $this->userId,
            'time' => time(),
        ]);
        if (!$topic_id) {
            $this->error('发表帖子失败');
        }

        $r = db('forum')->where('id', $forum_id)->update([
            'topicals_num' => $forum['topicals_num'] + 1,
            'last_time' => time(),
        ]);
        if (!$r) {
            $this->error('更新圈子帖子数量失败');
        }

        $this->success('发表帖子成功', [
            'topic_id' => $topic_id,
        ]);
    }

    /**
     * 回复帖子
     * 
     * - `topic_id` 帖子ID
     * - `reply_id` 回复ID(可选)
     * - `content` 帖子内容
     */
    function reply()
    {
        $topic_id = $_REQUEST['topic_id'] ?? 0;
        $reply_id = $_REQUEST['reply_id'] ?? 0;
        $content = trim($_REQUEST['content'] ?? '');

        if ($this->userId === 0) {
            return $this->error('请先登录');
        }

        if (mb_strlen($content) < 2) {
            $this->error('帖子内容太少');
        }

        $topic = db('forum_topic')->where('id', $topic_id)->find();
        if (!$topic) {
            $this->error('帖子不存在');
        }

        $forum = db('forum')->where('id', $topic['forum_id'])->find();
        if (!$forum) {
            $this->error('圈子不存在');
        }

        if ($reply_id) {
            $reply = db('forum_reply')->where('forum_id', $forum['id'])->where('id', $reply_id)->find();
            if (!$reply) {
                $this->error('回复不存在');
            }
        }

        $has = db('forum_user')->where('forum_id', $forum['id'])->where('uid', $this->userId)->count();
        if (!$has) {
            $this->error('您尚未加入该圈子，无法回复');
        }

        $new_reply_id = db('forum_reply')->insertGetId([
            'forum_id' => $forum['id'],
            'topic_id' => $topic_id,
            'reply_id' => $reply_id,
            'content' => $content,
            'uid' => $this->userId,
            'time' => time(),
        ]);
        if (!$new_reply_id) {
            $this->error('回帖失败');
        }

        $r = db('forum')->where('id', $forum['id'])->update([
            'replies_num' => $forum['replies_num'] + 1,
        ]);
        if (!$r) {
            $this->error('更新圈子回帖数量失败');
        }

        $r = db('forum_topic')->where('id', $topic['id'])->update([
            'replies_num' => $topic['replies_num'] + 1,
        ]);
        if (!$r) {
            $this->error('更新帖子回帖数量失败');
        }

        if ($reply_id) {
            $r = db('forum_reply')->where('id', $reply['id'])->update([
                'replies_num' => $reply['replies_num'] + 1,
            ]);
            if (!$r) {
                $this->error('更新回帖数量失败');
            }
        }

        $this->success('回帖成功', [
            'reply_id' => $new_reply_id,
        ]);
    }

    /**
     * 点赞
     *
     * - `topic_id` 帖子ID(二选其一)
     * - `reply_id` 回复ID(二选其一)
     */
    function good()
    {
        $reply_id = $_REQUEST['reply_id'] ?? 0;
        $topic_id = $_REQUEST['topic_id'] ?? 0;

        if ($reply_id) {
            $reply = db('forum_reply')->where('id', $reply_id)->find();
            if (!$reply) {
                $this->error('回复不存在');
            }
            db('forum_reply')->where('id', $reply_id)->update([
                'goods_num' => $reply['goods_num'] + 1
            ]);
            $this->success('点赞成功');
        } else if ($topic_id) {
            $topic = db('forum_topic')->where('id', $topic_id)->find();
            if (!$topic) {
                $this->error('帖子不存在');
            }
            $forum = db('forum')->where('id', $topic['forum_id'])->find();
            if (!$forum) {
                $this->error('圈子不存在');
            }
            db('forum_topic')->where('id', $topic_id)->update([
                'goods_num' => $topic['goods_num'] + 1
            ]);
            db('forum')->where('id', $forum['id'])->update([
                'goods_num' => $forum['goods_num'] + 1
            ]);
            $this->success('点赞成功');
        } else {
            $this->error('参数不足');
        }
    }

    /**
     * 删除帖子或回帖
     *
     * - `topic_id` 帖子ID(二选其一)
     * - `reply_id` 回复ID(二选其一)
     */
    function delete()
    {
        $reply_id = $_REQUEST['reply_id'] ?? 0;
        $topic_id = $_REQUEST['topic_id'] ?? 0;

        if ($this->userId === 0) {
            return $this->error('请先登录');
        }

        if ($reply_id) {
            $reply = db('forum_reply')->where('id', $reply_id)->where('uid', $this->userId)->find();
            if (!$reply) {
                $this->error('回复不存在');
            }
            db('forum_reply')->where('id', $reply_id)->delete();
            db('forum_reply')->where('reply_id', $reply_id)->delete();
            $this->success('删除回帖成功');
        } else if ($topic_id) {
            $topic = db('forum_topic')->where('id', $topic_id)->where('uid', $this->userId)->find();
            if (!$topic) {
                $this->error('帖子不存在');
            }
            db('forum_topic')->where('id', $topic_id)->delete();
            db('forum_reply')->where('topic_id', $topic_id)->delete();
            $this->success('删除帖子成功');
        } else {
            $this->error('参数不足');
        }
    }
}
